package xman.mjava.lang;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.log4j.Logger;

public class Jdbc {
    /*-
     * JDBC API DriveManager,Connection,Statement,PreparedStatment,ResutltSet
     */
    private static final Logger logger = Logger.getLogger(Jdbc.class);
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            logger.info("+++++++++load driver class success++++++++++++");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static Connection getConnection(String url, String user, String password) {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    
    public static void process(Connection conn, String sql) {
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // conn.setAutoCommit(false);
            // conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            // conn.setSavepoint(); //just some db support
            // conn.commit();
            // conn.rollback();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConnecttion(conn, stmt, rs);
        }
    }
    
    public static void closeConnecttion(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (rs != null)
                rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
